import requests, json
from datetime import datetime, timezone, timedelta
from dateutil import parser



def isodate2utcstamps(iso_date_time):
    # 将 ISO 8601 字符串转换为 datetime 对象
    dt = parser.parse(iso_date_time)
    timestamp = dt.timestamp()
    # print(timestamp)
    return timestamp


def get_image(harbor_url, repo_name, project_name, username, password):
    url = f"{harbor_url}/api/repositories/{repo_name}/{project_name}/tags?detail=1"
    response = requests.get(url, auth=(username, password))
    return response

# http://192.168.235.134:60195/api/repositories/demo/zookeeper/tags/3.9.5

def delete_image(harbor_url, repo_name, project_name, image_version, username, password):
    url = f"{harbor_url}/api/repositories/{repo_name}/{project_name}/tags/{image_version}"
    response = requests.delete(url, auth=(username, password))
    return response

def delete_single_image(harbor_url, repo_name, project_name, clean_time, username, password):
    ninety_days_ago = datetime.now() - timedelta(days=clean_time)

    timestamp_ninety_days_ago = ninety_days_ago.timestamp()

    print("{}天前的时间戳:{}".format(clean_time, timestamp_ninety_days_ago) )

    # for digest in digests:
    res1_dic = {}
    res1 = get_image(harbor_url, repo_name, project_name, username, password)
    # print(res1.text)
    res1_list = json.loads(res1.text)
    for res1_dic in res1_list:
        iso_date_time = res1_dic["created"]
        cur_timestamps = isodate2utcstamps(iso_date_time)
        if timestamp_ninety_days_ago > cur_timestamps:
            # delete_image(harbor_url, repo_name, project_name, image_version, username, password)
            print("开始清理镜像,镜像创建时间为：{}，镜像tag为：{}".format(iso_date_time, res1_dic["name"]))
            delete_image(harbor_url, repo_name, project_name, res1_dic["name"], username, password)


def get_repoId(harbor_url, repo_name, username, password):
    url = f"{harbor_url}/api/projects"
    response = requests.get(url, auth=(username, password))
    repo_res = json.loads(response.text)
    for repo_res_dic in repo_res:
        if repo_res_dic["name"] == repo_name:
            repoId = repo_res_dic["project_id"]
    return repoId

def get_projBy_repoId(harbor_url, repoId, username, password):
    repo_pro_list = []
    url = f"{harbor_url}/api/repositories?project_id={repoId}"
    response = requests.get(url, auth=(username, password))
    proj_res = json.loads(response.text)
    for proj_res_dic in proj_res:
        repo_pro_list.append(proj_res_dic["name"])
    return repo_pro_list

def main():
    repo_pro_list = []
    repo_list = ["scmv6", "scmv8", "sie6" ]
    project_list = []
    harbor_url = "http://harbor.irissz.com:60195"
    repo_name = "sie6"
    # project_name = "center-batch"
    # image_version = "504ee4b"
    username = "admin"
    password = "iris@Harbor2020"
    clean_time = 150
    repoId = get_repoId(harbor_url, repo_name, username, password)
    # print(repoId)
    repo_pro_list = get_projBy_repoId(harbor_url, repoId, username, password)
    for repo_pro_v in repo_pro_list:
        project_name = repo_pro_v.split("/")[1]
        print(f"仓库名字：{repo_name},项目名字：{project_name}")
        if project_name != "skywalking-agent":
            delete_single_image(harbor_url, repo_name, project_name, clean_time, username, password)




if __name__ == '__main__':
    main()